package com.yijumao.shop.controller;

import com.ramostear.captcha.HappyCaptcha;
import com.yijumao.shop.domain.User;
import com.yijumao.shop.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    //注册方法
    @RequestMapping("/register")
    public String login(User user,HttpSession session){
        userService.insert(user);
        //注册成功后默认登录并返回主页
        User login = userService.login(user.getUsername(), user.getPassword());
        session.setAttribute("user",user);
        return "redirect:/";
    }


    //登陆方法
    @RequestMapping("/login")
    public String login(String username, String password, String captcha, String rememberUser, Model model,
                        HttpServletRequest request, HttpSession session, HttpServletResponse response) {
        //创建保存用户名的cookie 默认为空
        Cookie cookieUserName = new Cookie("cookieUserName","");
        Cookie cookieUserPassword = new Cookie("cookieUserPassword","");
        if("true".equals(rememberUser)){
            //用户勾选记住用户名，存入cookie
            cookieUserName.setValue(username);
            cookieUserPassword.setValue(password);
            //生命周期一个月
            cookieUserName.setMaxAge(30*24*60*60);
            cookieUserPassword.setMaxAge(30*24*60*60);
            //rememberUser标记为true
            model.addAttribute("rememberUser","true");
        }else{
            // 否则将value置空
            cookieUserName.setValue("");
            cookieUserPassword.setValue("");
            /*
                此处不能销毁cookie
                //设置持久时间为0
                cookieUserName.setMaxAge(0);
            */
        }
        //设置共享路径 当前项目下都携带这个cookie
        cookieUserName.setPath(request.getContextPath());
        cookieUserPassword.setPath(request.getContextPath());
        //使用 HttpServletResponse 对象向客户端发送 Cookie
        response.addCookie(cookieUserName);
        response.addCookie(cookieUserPassword);

        boolean verification = HappyCaptcha.verification(request, captcha, true);
        if (!verification) {
            model.addAttribute("error", "验证码有误");
            return "login";
        }
        System.out.println(username+password);
        User user = userService.login(username, password);
        if (user == null) {
            model.addAttribute("error", "用户名或密码错误");
            return "login";
        }else {
            //登陆成功 将error清空
            model.addAttribute("error","");
            session.setAttribute("user", user);
            return "redirect:/";
        }
    }
}
